//
//  TSReorderColumnViewController.m
//  CLGReorderColumnDemo
//
//  Created by GuochengLiu on 2016/11/20.
//  Copyright © 2016年 sumavision. All rights reserved.
//

#import "TSReorderColumnViewController.h"
#import "TSColumnCell.h"
#import <UIImageView+WebCache.h>
#import <AFNetworking.h>


NSString *serverURL = @"http://192.168.3.102:8000/";

@interface TSReorderColumnViewController ()

@end

@implementation TSReorderColumnViewController
{
    NSArray *_arrayServerColumn;    // 服务端栏目返回
    
    NSMutableArray *_arrayReorderedColumn;  // 通过本地排序后的栏目（过滤掉下线的栏目）
    NSMutableArray *_arrayHiddenColumn; // 隐藏的栏目（过滤掉下线的栏目）
    
    NSArray <NSMutableArray *> *_arrayData;            // 最终显示的栏目数据（_arrayReorderedColumn + _arrayHiddenColumn）
}

static NSString * const reuseIdentifier = @"TSColumnCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"TSColumnCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    // get Data
    [self reloadContent];
}

- (void)reloadContent
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/columns.json", serverURL]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
            
            
            _arrayServerColumn = [responseObject valueForKey:@"liveCategoryList"];
            
            _arrayReorderedColumn = [[self getReorderedColumn:_arrayServerColumn] mutableCopy];
            
            _arrayHiddenColumn = [[self getHiddenColumn] mutableCopy];
            
            _arrayData = @[_arrayReorderedColumn, _arrayHiddenColumn];
            
            [self.collectionView reloadData];
            
        }
    }];
    [dataTask resume];
}


- (NSArray *)getReorderedColumn:(NSArray *)arrayOriginalColumn
{
    NSArray *arraySavedColumn = [[NSUserDefaults standardUserDefaults] valueForKey:@"TSSavedColumn"];
    
    if (arraySavedColumn == nil) {
        return arrayOriginalColumn;
    }
    
    NSMutableArray *arrayReorderedColumn = [NSMutableArray array];
    
    for (NSDictionary *columnDict in arraySavedColumn) {
        NSString *columnId = [columnDict valueForKey:@"categoryID"];
        
        NSInteger index = [self isColumnOnline:columnId arrayServerColumn:_arrayServerColumn];
        if (index != -1) {
            [arrayReorderedColumn addObject:[_arrayServerColumn objectAtIndex:index]];
        }
    }
    
    return arrayReorderedColumn;
}


- (NSInteger)isColumnOnline:(NSString *)column arrayServerColumn:(NSArray *)arrayServerColumn{
    
    NSInteger index = -1;
    
    
    for (NSDictionary *columnItem in arrayServerColumn) {
        if ([column isEqualToString:[columnItem valueForKey:@"categoryID"]]) {
            index = [arrayServerColumn indexOfObject:columnItem];
        }
    }
    return index;
}

- (NSArray *)getHiddenColumn
{
    NSArray *arraySavedColumn = [[NSUserDefaults standardUserDefaults] valueForKey:@"TSHiddenColumn"];
    NSMutableArray *arrayHiddenColumn  = [NSMutableArray array];

    for (NSDictionary *columnItem in arraySavedColumn) {
        NSString *columnId = [columnItem valueForKey:@"categoryID"];
        
        NSInteger index = [self isColumnOnline:columnId arrayServerColumn:_arrayServerColumn];
        
        if (index != -1) {
            [arrayHiddenColumn addObject:[_arrayServerColumn objectAtIndex:index]];
        }
    }
    return arrayHiddenColumn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _arrayData.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_arrayData[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TSColumnCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    NSDictionary *dict = _arrayData[indexPath.section][indexPath.row];
    
    NSString *name = [dict valueForKey:@"categoryName"];
    NSString *imageUrl = [dict valueForKey:@"imageUrl"];
    
    imageUrl = [NSString stringWithFormat:@"%@/%@", serverURL, imageUrl];
    imageUrl = [imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [cell.columnName setText:name];
    [cell.columnImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>


- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath {
    
    
    id item = _arrayData[fromIndexPath.section][fromIndexPath.row];
    
    NSInteger sourceSection = fromIndexPath.section;
    NSMutableArray *arraySource = _arrayData[sourceSection];
    
    [arraySource removeObject:item];
    
    NSInteger destSection = toIndexPath.section;
    NSMutableArray *arrayDest = _arrayData[destSection];
    
    [arrayDest insertObject:item atIndex:toIndexPath.row];
    
    
    [self saveColumnsOrder];
}

- (void)saveColumnsOrder
{
    [[NSUserDefaults standardUserDefaults] setValue:_arrayReorderedColumn forKey:@"TSSavedColumn"];
    
    
    [[NSUserDefaults standardUserDefaults] setValue:_arrayHiddenColumn forKey:@"TSHiddenColumn"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSIndexPath *destIndexPath;
    
    if (indexPath.section == 0 && indexPath.row < 2) {
        return;
    }
    
    id item = _arrayData[indexPath.section][indexPath.row];
    
    if (indexPath.section == 0) {
        
        NSArray *arraySourceSection = _arrayData[0];
        NSArray *arrayDestSection = _arrayData[1];
        
        destIndexPath = [NSIndexPath indexPathForRow:arrayDestSection.count inSection:1];
        
        [collectionView performBatchUpdates:^{
            
            NSMutableArray *arraySource = _arrayData[indexPath.section];
            [arraySource removeObject:item];
            NSMutableArray *arrayDest = _arrayData[destIndexPath.section];
            [arrayDest addObject:item];
            
            [collectionView moveItemAtIndexPath:indexPath toIndexPath:destIndexPath];
        } completion:^(BOOL finished) {
            if (finished) {
                [self saveColumnsOrder];
            }
        }];
        
    } else {
        
        NSArray *arraySourceSection = _arrayData[1];
        NSArray *arrayDestSection = _arrayData[0];
        
        destIndexPath = [NSIndexPath indexPathForRow:arrayDestSection.count inSection:0];
        
        [collectionView performBatchUpdates:^{
            
            
            NSMutableArray *arraySource = _arrayData[indexPath.section];
            [arraySource removeObject:item];
            
            NSMutableArray *arrayDest = _arrayData[destIndexPath.section];
            [arrayDest addObject:item];
            
            [collectionView moveItemAtIndexPath:indexPath toIndexPath:destIndexPath];
        } completion:^(BOOL finished) {
            if (finished) {
                [self saveColumnsOrder];
            }
        }];
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row < 2) {
        return NO;
    } else {
        return YES;
    }
}


@end
